package com.zzptc.syl.traffic;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;

import java.sql.Time;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class Account extends AppCompatActivity {
    private static final String TAG = "Account";
    private ListView listView;
    private List<Car> dataBeans = null;
    private AccountAdapter accountAdapter;
    private Button btbatch;
    private List<Car.DataBean> list;
    private CheckBox box;
    private ImageView signalImg;
    private Handler handler = new Handler(Objects.requireNonNull(Looper.myLooper())) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 0:
                    signalImg.setBackgroundResource(R.drawable.not_signal);
                    break;
                case 1:
                    signalImg.setBackgroundResource(R.drawable.wifi_signal);
                    break;
                case 2:
                    signalImg.setBackgroundResource(R.drawable.signal_2g);
                    break;
                case 3:
                    signalImg.setBackgroundResource(R.drawable.signal_3g);
                    break;
                case 4:
                    signalImg.setBackgroundResource(R.drawable.signal_4g);
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_account);
        initview();

        btbatch=findViewById(R.id.bt_batch);
        btbatch.setOnClickListener(view -> {
            StringBuilder builder = new StringBuilder();
            for (Car.DataBean dataBean: list){
                if (dataBean.isSelect()){
                    builder.append("&").append("carno=").append(dataBean.getCarno());
                }
            }
            if (builder.length()==0){
                Toast.makeText(this, "请勾选充值对象", Toast.LENGTH_SHORT).show();
            } else {
                show(builder.toString().substring(1));
            }
        });
        Retrofit retrofit=new Retrofit.Builder()
                .baseUrl("http://hh1.me:5001/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        Map<String,String> map=new HashMap<>();
        map.put("who","张三");
        map.put("carno","辽A10001");
        map.put("amount","1");
        RequestBody body=RequestBody.create(MediaType.parse("application/json;charset=utf_8"),new Gson().toJson(map));
        Carservice carservice=retrofit.create(Carservice.class);
        Call<Car> car=carservice.geta();
        car.enqueue(new Callback<Car>() {
            @Override
            public void onResponse(Call<Car> call, Response<Car> response) {
                list=response.body().getData();
                accountAdapter = new AccountAdapter(list,Account.this);
                listView.setAdapter(accountAdapter);
            }

            @Override
            public void onFailure(Call<Car> call, Throwable t) {

            }
        });
    }
    private void initview() {
        listView=findViewById(R.id.lv_card);

        box=findViewById(R.id.ck_yes);
    }
    public class AccountAdapter extends BaseAdapter {
        private List<Car.DataBean> carList;
        private Context context;

        public AccountAdapter(List<Car.DataBean> carList,Context context){
            this.carList=carList;
            this.context=context;
        }
        @Override
        public int getCount() {
            return carList.size();
        }

        @Override
        public Object getItem(int i) {
            return null;
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view1, ViewGroup viewGroup) {
            View view=null;
//            if(view1==null) {
                view = LayoutInflater.from(context).inflate(R.layout.row2, viewGroup, false);
//            }else {
//                view=view1;
//            }
                ImageView logo = (ImageView) view.findViewById(R.id.iv_oip);
                TextView number1 = (TextView) view.findViewById(R.id.tv_number1);
                TextView number2 = (TextView) view.findViewById(R.id.tv_number2);
                TextView money = (TextView) view.findViewById(R.id.tv_money);
                RelativeLayout row2=(RelativeLayout) view.findViewById(R.id.rl_all2);
                CheckBox yes = (CheckBox) view.findViewById(R.id.ck_yes);
                Button recharge = (Button) view.findViewById(R.id.bt_Recharge);
                //logo.secetBackgroundResour(carList.get(i).getData().get(0).getCarplate());
                if (list.get(i).getAmount()<2000){
                    row2.setBackgroundColor(Color.parseColor("#B22222"));
                }
                number1.setText(String.valueOf(carList.get(i).getCarno()));
            Log.d(TAG, "getView: "+carList.get(i).getCarno());
                number2.setText(String.valueOf(carList.get(i).getWho()));
                money.setText(String.valueOf(carList.get(i).getAmount()));
                recharge.setOnClickListener(view2 -> {
                    show(carList.get(i).getCarno());
                });
                yes.setOnCheckedChangeListener(
                        (compoundButton, b) -> list.get(i).setSelect(b));


            return view;
        }
    }
    public void show(String carnumber){
        Timer timer = new Timer();
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                Message message = new Message();
                message.what = NetWorkUtils.getAPNType(Account.this);
                handler.sendMessage(message);
            }
        };
        timer.schedule(timerTask, 0, 2000);
        android.app.AlertDialog.Builder builder=new android.app.AlertDialog.Builder(this);
        final AlertDialog dialog=builder.create();
        View diaview = View.inflate(this,R.layout.activity_dialog,null);
        signalImg = diaview.findViewById(R.id.signalImg);
        TextView money1=(TextView) diaview.findViewById(R.id.et_money1);
        EditText moneyC= diaview.findViewById(R.id.et_money2);
        Button btMoney =(Button) diaview.findViewById(R.id.bt_money);
        Button btNo=(Button) diaview.findViewById(R.id.bt_no);
        String carno = carnumber.replaceAll("carno=", " ").replaceAll("&", "");
        money1.setText(carno);
        dialog.setView(diaview);
        dialog.show();
        dialog.getWindow().setLayout(1300,900);
        btMoney.setOnClickListener(view -> {
            timer.cancel();
            timerTask.cancel();
            queryRecharge(carnumber,moneyC.getText().toString(),this);
            dialog.dismiss();
        });
        btNo.setOnClickListener(view -> {
            timer.cancel();
            timerTask.cancel();
            dialog.dismiss();
        });
    }

    public void queryRecharge(String carno, String money, Context context){
        Retrofit retrofit=new Retrofit.Builder()
                .baseUrl("http://hh1.me:5001/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        Carservice carservice =retrofit.create(Carservice.class);
        Map<String,String> map=new HashMap<>();
        map.put("who","");
        map.put("carno",carno);
        map.put("amount",money);
       RequestBody body=RequestBody.create(MediaType.parse("application/json;charset=utf_8"),new Gson().toJson(map));
//        Call<Car> car= carservice.car(body);
        Call<Car> car = carservice.getCar(map);
        car.enqueue(new Callback<Car>() {
            @Override
            public void onResponse(Call<Car> call, Response<Car> response) {
                Toast.makeText(context, "充值成功", Toast.LENGTH_SHORT).show();
            }
            @Override
            public void onFailure(Call<Car> call, Throwable t) {
                throw new RuntimeException(t.getMessage());
            }
        });
    }

}
